package chapter06;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

@Slf4j
public class AtomicArrayTest {

    public static void main(String[] args) {
        demo(
                ()->new int[10],
                (array)->array.length,
                (array)->(index)->array[index]++,
                (array)-> log.debug("结果{}",array)
        );
        demo(
                ()->new AtomicIntegerArray(10),
                (array)->array.length(),
                (array)->(index)->array.getAndIncrement(index),
                (array)-> log.debug("结果{}",array)
        );
    }

    public static <T> void demo(Supplier<T> arraySupplier,
                                Function<T,Integer> lengthFun,
                                Function<T,Function<Integer,Object>> putConSumer,
                                Consumer<T> printConsumer){
        List<Thread> list=new ArrayList<>();
        T array=arraySupplier.get();
        int length=lengthFun.apply(array);
        for(int i=0;i<length;i++){
            for(int j=0;j<10000;j++){
                putConSumer.apply(array).apply(j%length);
            }
        }
        list.forEach(Thread::start);
        for (Thread thread : list) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        printConsumer.accept(array);

    }
}

